package apps.softtech.fastmarket;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ViewFlipper;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.RequestDataFromServer;
import apps.softtech.fastmarket.adapter.AdapterTheirProduct;
import apps.softtech.fastmarket.adapter.AdapterTheirProfileFollower;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.FollowProduct;
import apps.softtech.fastmarket.model.FollowUser;
import apps.softtech.fastmarket.model.Product;
import apps.softtech.fastmarket.model.UserInfo;

public class ActivityTheirProfile extends Activity{
	Button btFollower, btProduct;
	Button btFollow;
	ListView lvFollwer,lvProduct;
	/**
	 * follwer 
	 */
	ArrayList<FollowUser> mFollowerList = new ArrayList<FollowUser>();
	ArrayList<UserInfo> mUserInfosList = new ArrayList<UserInfo>();
	AdapterTheirProfileFollower maAdapterTheirProfileFollower;
	/**
	 * product
	 */
	ArrayList<FollowProduct> mFollowProducts = new ArrayList<FollowProduct>();
	ArrayList<Product> mProductsList = new ArrayList<Product>();
	AdapterTheirProduct mAdapterTheirProduct;
	/**
	 * options display
	 */
	DisplayImageOptions options;
	/**
	 * connect internet
	 */
	ConnectionDetector cd = new ConnectionDetector(ActivityTheirProfile.this);
	/**
	 * database
	 */
	DatabaseHandler dbh = new DatabaseHandler(ActivityTheirProfile.this);
	/**
	 * get their id
	 */
	ViewFlipper vfTheirProduct;
	int theirId=1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_their_profile);
		/**
		 * init imagloader
		 */
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				ActivityTheirProfile.this).build();
		ImageLoader.getInstance().init(config);
		/**
		 * init options
		 */
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.ic_launcher)
		.showImageForEmptyUri(R.drawable.ic_launcher)
		.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.displayer(new RoundedBitmapDisplayer(20)).build();
		
		new RegisterGoogleCM(ActivityTheirProfile.this).registerGCM();
		
	init();
	initFunction();
	}
	/**
	 * init
	 */
	private void init() {
		btFollower = (Button)findViewById(R.id.btTheirProfileFollower);
		btProduct = (Button)findViewById(R.id.btTheirProfileTheirProduct);
		btFollow = (Button)findViewById(R.id.btTheirProfileFollowing);
		
		lvFollwer = (ListView)findViewById(R.id.lvTheirFollowr);
		lvProduct = (ListView)findViewById(R.id.lvTheirProduct);
		
		vfTheirProduct = (ViewFlipper)findViewById(R.id.vfTheirProfile);
	}
	/**
	 * init function
	 */
	private void initFunction() {
		btFollow.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
			}
		});
		btFollower.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				mFollowerList.clear();
				setDataFollower();
				if(cd.isConnectingToInternet()){
					//load data
					setDataOnline();
				}else{
					//load local data
					setDataLocal();
				}
			}
			
		});
		btProduct.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mFollowProducts.clear();
				setDataProduct();
				if(cd.isConnectingToInternet()){
					new AsyncTaskGetProduct().execute();
				}else{
					mFollowProducts.clear();
					mProductsList.clear();
					mProductsList = (ArrayList<Product>) dbh.getProduct(null, 
							Product.USERID+ " =?", new String[]{""+theirId}, null, null);
					setDataProduct();
				}
			}
		});
	}
	/**
	 * set data follower
	 */
	private void setDataFollower() {
		maAdapterTheirProfileFollower = new AdapterTheirProfileFollower(ActivityTheirProfile.this,
				mUserInfosList, options);
		lvFollwer.setAdapter(maAdapterTheirProfileFollower);
		vfTheirProduct.setInAnimation(ActivityTheirProfile.this, R.anim.in_from_right);
		vfTheirProduct.setDisplayedChild(0);
	}
	
	/**
	 * show data local
	 */
	private void setDataLocal(){
		mUserInfosList.clear();
		mFollowerList.clear();
		mFollowerList = (ArrayList<FollowUser>) dbh.getFollowUser(null, FollowUser.TO_USER_ID + 
				" =?" , new String[]{""+theirId}, null, null);
		if(mFollowerList.size()!=0){
			for(int i=0;i<mFollowerList.size();i++){
			int idUser = mFollowerList.get(i).getFromUserId();
				mUserInfosList = (ArrayList<UserInfo>) dbh.getUserInfo(null,
						UserInfo.USERID + " =?", new String[]{""+idUser}, null, null);
			}
			setDataFollower();
			}
	}
	/**
	 * show data product
	 */
	private void setDataProduct(){
		mAdapterTheirProduct  = new AdapterTheirProduct(ActivityTheirProfile.this, mProductsList, options);
		lvProduct.setAdapter(mAdapterTheirProduct);
		vfTheirProduct.setInAnimation(ActivityTheirProfile.this, R.anim.in_from_right);
		vfTheirProduct.setDisplayedChild(1);
		
	}
	/**
	 * set data online
	 */
	private void setDataOnline(){
		mUserInfosList.clear();
		mFollowerList.clear();
		dbh.deleteFollowUser(FollowUser.FOLLOW_ID + " >=0", null);
		dbh.deleteUserInfo(UserInfo.USERID + " >=0", null);
		new AsyncTaskGetFollower().execute();
	}
	
	@Override
	protected void onDestroy() {
		dbh.close();
		super.onDestroy();
	}
	
	/**
	 * request user follower
	 */
	class AsyncTaskGetFollower extends AsyncTask<Void, Void, Void>{
		ProgressDialog pd;
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityTheirProfile.this);
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			try {
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer()
								.requestMyProfileFollowing(theirId));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						dbh.insertFollowUser(new FollowUser(jsonList
								.getInt("st_FromUserId"), jsonList
								.getInt("st_ToUserId"), jsonList
								.getString("st_FollowDate"), jsonList
								.getInt("st_GetNotification")));
						mFollowerList.add(new FollowUser(jsonList
								.getInt("st_FromUserId"), jsonList
								.getInt("st_ToUserId"), jsonList
								.getString("st_FollowDate"), jsonList
								.getInt("st_GetNotification")));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			
			if(mFollowerList.size()!=0){
				for(int i=0;i<mFollowerList.size();i++){
				int idUser = mFollowerList.get(i).getFromUserId();
					new AsyncTaskGetUserInfo().execute(idUser);
				}
				setDataFollower();
				}
			pd.dismiss();
			super.onPostExecute(result);
		}
		
	}
	/**
	 * request user
	 */
	class  AsyncTaskGetUserInfo extends AsyncTask<Integer, Void, Void>{

		@Override
		protected Void doInBackground(Integer... params) {
			try {
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(
						new RequestDataFromServer().requestUserInfoById(params[0]));
				int success = jsonCategoryParentList.getInt("success");
				if (success == 1) {
					jsonData = jsonCategoryParentList.getJSONArray("data");
					for (int i = 0; i < jsonData.length(); i++) {
						JSONObject jsonList = new JSONObject(jsonData
								.getJSONObject(i).toString());
						UserInfo uit = new UserInfo();
						uit.setUserName(jsonList.getString("st_UserName"));
						uit.setAvatarPath(jsonList.getString("st_AvatarPath"));
						uit.setSt_UserId(params[0]);
						uit.setEmail(jsonList.getString("st_Email"));
						uit.setPhoneNumber(jsonList.getString("st_PhoneNumber"));
						dbh.insertUserInfo(uit);
						mUserInfosList.add(uit);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	/**
	 * get data product
	 */
	class AsyncTaskGetProduct extends AsyncTask<Void, Void, Void>{
		ProgressDialog pd;
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityTheirProfile.this);
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			try{
				JSONArray jsonData = new JSONArray();
				JSONObject jsonCategoryParentList = new JSONObject(new RequestDataFromServer().requestGetProductById(theirId));
				int success = jsonCategoryParentList.getInt("success");
				if(success==1){
					jsonData = jsonCategoryParentList.getJSONArray("data");
					Log.v("", jsonData.toString());
					for(int i=0;i<jsonData.length();i++){
						JSONObject jsonList = new JSONObject(jsonData.getJSONObject(i).toString());
//						
						Product mpProduct = new Product();
						mpProduct.setPrice(jsonList.getInt("st_Price"));
						mpProduct.setAvatarPath(jsonList.getString("st_AvatarPath"));
						mpProduct.setCreatedDate(jsonList.getString("st_CreatedDate"));
						dbh.insertProduct(mpProduct);
						mProductsList.add(mpProduct);
					}
				}
				}catch(Exception e){}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			setDataProduct();
			pd.dismiss();
			super.onPostExecute(result);
		}
		
	}
	class AsyncTaskFollow extends AsyncTask<Void, Void, Void>{
		ProgressDialog pd;
		int success;
		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivityTheirProfile.this);
			pd.setMessage("Loading....");
			pd.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			try {
				JSONObject json = new JSONObject(new RequestDataFromServer().requestFollowUser(ApplicationConstants.MY_USER, theirId));
			  success = json.getInt("success");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			if(success==1){
				btFollow.setText(getResources().getString(R.string.unfollow));
			}
			pd.dismiss();
			super.onPostExecute(result);
		}
		
	}

}
